import json
import base64
import os
import re
import chuankou
import time
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.asr.v20190614 import asr_client, models
try:
    cred = credential.Credential("AKIDDG2XnmUxA6l9F5evvf8KEtHOFxOYR3QW", "pPjmY4KJ1TeZDagV3KK4XjeIhpWx94i4")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "asr.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = asr_client.AsrClient(cred, "", clientProfile)
    f = os.popen("transform.bat")
    time.sleep(0.5)
    filename="录音.wav"
    #filename = "test.aac"
    #filename = "test.wav"
    #按需启用以上三个之一
    file1=open(filename,"rb").read()
    text=base64.b64encode(file1).decode("utf-8")#base64编码

    req = models.SentenceRecognitionRequest()
    params = {
        "ProjectId": 1,
        "SubServiceType": 2,
        "EngSerViceType": "16k_zh",
        "SourceType": 1,
        "VoiceFormat": "wav",
        "UsrAudioKey": "123",
        "Data": text
    }
    req.from_json_string(json.dumps(params))

    resp = client.SentenceRecognition(req)
    ans = resp.to_json_string().split(',',5)[0]
    ans=re.sub("[A-Za-z0-9\{\:\"\，\。]","",ans)#剔除字符串中的英文字母和符号

    a=[0]#随便搞个变量

    if(ans.find("水杯")!=-1):
        a=[0xAA,0x55,0x1,0xff]
        print(a)
    elif (ans.find("盘子") != -1):
        a=[0xAA,0x55,0x2,0xff]
        print(a)
    else:
        a=[0]
        print("未识别到有效物品")

    #print(ans)
    #print(resp.to_json_string().split(',',5)[0])#字符串按’，‘分割为5个部分，只打印第一个部分,也就是result部分
    #f=open("result.txt",'w')
    #f.write(resp.to_json_string().split(',',5)[0])
    #f.write(ans)
    #f.write("1")
    #f.close()
    os.remove("录音.wav")#删除掉语音文件

    if(a!=0):
        chuankou.port_open_recv()
        chuankou.send(a)



except TencentCloudSDKException as err:
    print(err)